package com.haitaoit.chengquan.module.home.activity.maintenance;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ScrollView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.haitaoit.chengquan.R;
import com.haitaoit.chengquan.base.BaseActivity;
import com.haitaoit.chengquan.module.home.activity.fabu.SendNeedActivity;
import com.haitaoit.chengquan.module.home.activity.maintenance.adapter.FacilityMainenanceAdapter;
import com.haitaoit.chengquan.module.home.model.FacilityMainenanceModel;
import com.haitaoit.chengquan.utils.Constant;
import com.haitaoit.chengquan.utils.DateTimeUtil;
import com.haitaoit.chengquan.utils.GetSign;
import com.haitaoit.chengquan.utils.HttpUtilsSingle;
import com.haitaoit.chengquan.utils.NameValuePairSign;
import com.haitaoit.chengquan.utils.PreferenceUtils;
import com.haitaoit.chengquan.utils.ToastUtils;
import com.haitaoit.chengquan.view.MyListView;
import com.haitaoit.chengquan.view.PullToRefreshBase;
import com.haitaoit.chengquan.view.PullToRefreshScrollView;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

public class FacilityMaintenanceActivity extends BaseActivity implements PullToRefreshBase.OnRefreshListener<ScrollView> {
    @ViewInject(R.id.pull_to_refresh_scrollview)
    PullToRefreshScrollView pull_to_refresh_scrollview;
    @ViewInject(R.id.search_et)
    EditText search_et;

    private ScrollView mScrollView;
    private LinearLayout null_information_layout;
    private MyListView listView;


    private boolean isFrist = true;
    private int page = 1;
    private FacilityMainenanceAdapter adapter;
    private int title_type = 1, type_id_ser = 0, type_id_need = 0;

    private String account_type;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView_V(R.layout.activity_facility_maintenance);
        setLeftShow(1, R.mipmap.left);
        setRightShow(0, R.string.app_empty);
        backLeft_V();
        ViewUtils.inject(this);

        account_type= PreferenceUtils.getPrefString("account_type","");
        View view = LayoutInflater.from(this).inflate(R.layout.scrollview_listview_layout, null);
        null_information_layout = (LinearLayout) view.findViewById(R.id.null_information_layout);
        listView = (MyListView) view.findViewById(R.id.scrollview_listview);

        pull_to_refresh_scrollview.setPullLoadEnabled(true);
        pull_to_refresh_scrollview.setPullRefreshEnabled(true);
        pull_to_refresh_scrollview.setOnRefreshListener(this);
        pull_to_refresh_scrollview.setLastUpdatedLabel(DateTimeUtil
                .getFormatDateTime(DateTimeUtil.getCurrTimestamp()));
        mScrollView = pull_to_refresh_scrollview.getRefreshableView();
        mScrollView.setFillViewport(true);
        mScrollView.setVerticalScrollBarEnabled(false);
        mScrollView.addView(view);

        adapter = new FacilityMainenanceAdapter(this);
        adapter.setType(title_type);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Intent intent = new Intent();
                if (title_type == 1) {// 找服务
                    intent.setClass(FacilityMaintenanceActivity.this, ServerDetailActivity.class);
                } else if (title_type == 2) {// 找需求
                    intent.setClass(FacilityMaintenanceActivity.this, SeachDemandActivity.class);
                }
                intent.putExtra("id", adapter.getList().get(position).getId());
                startActivity(intent);
            }
        });

        int type_id = getIntent().getIntExtra("type_id", 0);
        if (type_id == 1) {
            setTitle_V("设备维修");
            type_id_ser = 1;
//            title_type = 2;
//            type_id_need = 1;
//            adapter.setType(title_type);
//            right.setVisibility(View.VISIBLE);
//            search_server.setVisibility(View.GONE);
//            search_maintenance.setChecked(true);
//            httpGetdemand_list(Constant.Getdemand_list);
        } else if (type_id == 2) {
            type_id_ser = 2;
            setTitle_V("加工订单");
        } else if (type_id == 3) {
            type_id_ser = 3;
            setTitle_V("机床耗材");
        } else if (type_id == 4) {
            type_id_ser = 4;
            setTitle_V("机床配件");
        } else if (type_id == 5) {
            type_id_ser = 5;
            setTitle_V("机床组立");
        } else if (type_id == 6) {
            type_id_ser = 6;
            setTitle_V("二手设备买卖");
        } else if (type_id == 7) {
            type_id_ser = 7;
            setTitle_V("二手设备改造");
        }
        httpGetdemand_list(Constant.Getservice_list);
    }

    // 发布成功返回刷新
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 15 && resultCode == 1) {
            isFrist = true;
            page = 1;
            if (title_type == 1) {
                httpGetdemand_list(Constant.Getservice_list);
            } else if (title_type == 2) {
                httpGetdemand_list(Constant.Getdemand_list);
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    @OnClick({R.id.right, R.id.search_img, R.id.search_server, R.id.search_maintenance})
    public void onClick(View v) {
        Intent intent = new Intent();
        switch (v.getId()) {
            case R.id.right:
               /* if (title_type == 1) {// 发布服务
                    intent.setClass(FacilityMaintenanceActivity.this, SendServiceActivity.class);
                } else */
                if (title_type == 2) {// 发布需求
                    intent.setClass(FacilityMaintenanceActivity.this, SendNeedActivity.class);
                    startActivityForResult(intent, 15);
                }
                break;
            case R.id.search_img:
                isFrist = true;
                page = 1;
                if (title_type == 1) {
                    httpGetdemand_list(Constant.Getservice_list);
                } else if (title_type == 2) {
                    httpGetdemand_list(Constant.Getdemand_list);
                }
                break;
            case R.id.search_server:
                title_type = 1;

               if(account_type!=null&&account_type.equals("1")){
                   setRightShow(0, R.string.app_empty);
               }

                // 0全部2加工订单3机床耗材4机床配件5机床组立6二手设备买卖7二手设备改造
                // 0全部1设备维修2机床耗材3机床组立4机床配件5加工订单6二手货设备买卖7二手货设置改造
                if (type_id_need == 1) {
                    type_id_ser = 1;
                } else if (type_id_need == 2) {
                    type_id_ser = 3;
                } else if (type_id_need == 3) {
                    type_id_ser = 5;
                } else if (type_id_need == 4) {
                    type_id_ser = 4;
                } else if (type_id_need == 5) {
                    type_id_ser = 2;
                } else if (type_id_need == 6) {
                    type_id_ser = 6;
                } else if (type_id_need == 7) {
                    type_id_ser = 7;
                }
                adapter.setType(title_type);
                isFrist = true;
                page = 1;
                httpGetdemand_list(Constant.Getservice_list);
                break;
            case R.id.search_maintenance:
                title_type = 2;
                setRightShow(0, R.string.fabu);
                // 0全部2加工订单3机床耗材4机床配件5机床组立6二手设备买卖7二手设备改造
                // 0全部1设备维修2机床耗材3机床组立4机床配件5加工订单6二手货设备买卖7二手货设置改造
                if (type_id_ser == 1) {
                    type_id_need = 1;
                } else if (type_id_ser == 2) {
                    type_id_need = 5;
                } else if (type_id_ser == 3) {
                    type_id_need = 2;
                } else if (type_id_ser == 4) {
                    type_id_need = 4;
                } else if (type_id_ser == 5) {
                    type_id_need = 3;
                } else if (type_id_ser == 6) {
                    type_id_need = 6;
                } else if (type_id_ser == 7) {
                    type_id_need = 7;
                }
                adapter.setType(title_type);
                isFrist = true;
                page = 1;
                httpGetdemand_list(Constant.Getdemand_list);
                break;
        }
        super.onClick(v);
    }

    private void httpGetdemand_list(String url) {
        int type_id = 0;
        if (title_type == 1) {
            type_id = type_id_ser;
        } else if (title_type == 2) {
            type_id = type_id_need;
        }
        String location_city = PreferenceUtils.getPrefString("location_city", "");
        List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();
        list.add(new NameValuePairSign("type", type_id + ""));
        list.add(new NameValuePairSign("name", search_et.getText().toString()));
        list.add(new NameValuePairSign("address", location_city));
        list.add(new NameValuePairSign("page", page + ""));
        list.add(new NameValuePairSign("pagesize", Constant.PageSize));
        String sign = GetSign.genPackageSign(list);

        RequestParams params = new RequestParams();
        params.addQueryStringParameter("type", type_id + "");
        params.addQueryStringParameter("name", search_et.getText().toString());
        params.addQueryStringParameter("address", location_city);
        params.addQueryStringParameter("page", page + "");
        params.addQueryStringParameter("pagesize", Constant.PageSize);
        params.addQueryStringParameter("sign", sign);

        HttpUtilsSingle.doGet(this, false, url, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                String result = arg0.result.toString();
                List<FacilityMainenanceModel> new_list = new ArrayList<FacilityMainenanceModel>();
                try {
                    JSONObject json = new JSONObject(result);
                    String Errcode = json.getString("ErrCode");
                    String Errmsg = json.getString("ErrMsg");
                    String Response = json.getString("Response");
                    Gson gson = new Gson();
                    switch (Integer.valueOf(Errcode)) {
                        case 1:// 失败
                            ToastUtils.showToast(Errmsg);
                            pull_to_refresh_scrollview.onPullDownRefreshComplete();
                            pull_to_refresh_scrollview.onPullUpRefreshComplete();
                            new_list = new ArrayList<FacilityMainenanceModel>();
                            break;
                        case 0:// 成功
                            new_list = gson.fromJson(Response,
                                    new TypeToken<List<FacilityMainenanceModel>>() {
                                    }.getType());
                            break;
                        case 2:// 暂无内容
                            pull_to_refresh_scrollview.onPullDownRefreshComplete();
                            pull_to_refresh_scrollview.onPullUpRefreshComplete();
                            new_list = new ArrayList<FacilityMainenanceModel>();
                            break;
                    }
                    if (isFrist) {
                        if (isNullDate(new_list)) {
                            adapter.setList(new_list);
                            adapter.notifyDataSetChanged();
                        }
                        pull_to_refresh_scrollview.onPullDownRefreshComplete();
                    } else {
                        List<FacilityMainenanceModel> allList = adapter.getList();
                        allList.addAll(new_list);
                        adapter.setList(allList);
                        adapter.notifyDataSetChanged();
                        pull_to_refresh_scrollview.onPullUpRefreshComplete();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(HttpException arg0, String arg1) {
                ToastUtils.showToast("获取数据失败,请检查网络");
            }
        });
    }

    /**
     * @tab 判断listview是否有值
     */
    private boolean isNullDate(List<FacilityMainenanceModel> rewordList) {
        if (rewordList == null || rewordList.size() == 0) {
            null_information_layout.setVisibility(View.VISIBLE);
            listView.setVisibility(View.GONE);
            return false;
        } else {
            null_information_layout.setVisibility(View.GONE);
            listView.setVisibility(View.VISIBLE);
            return true;
        }
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) {
        pull_to_refresh_scrollview.setLastUpdatedLabel(DateTimeUtil
                .getFormatDateTime(DateTimeUtil.getCurrTimestamp()));
        isFrist = true;
        page = 1;
        if (title_type == 1) {
            httpGetdemand_list(Constant.Getservice_list);
        } else if (title_type == 2) {
            httpGetdemand_list(Constant.Getdemand_list);
        }
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {
        pull_to_refresh_scrollview.setLastUpdatedLabel(DateTimeUtil
                .getFormatDateTime(DateTimeUtil.getCurrTimestamp()));
        isFrist = false;
        page++;
        if (title_type == 1) {
            httpGetdemand_list(Constant.Getservice_list);
        } else if (title_type == 2) {
            httpGetdemand_list(Constant.Getdemand_list);
        }
    }
}
